import 'dart:ffi';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:wx_faxian/const.dart';
import 'package:wx_faxian/pages/discover/child_page.dart';
import 'package:wx_faxian/pages/friends/friends_Data.dart';
import 'package:wx_faxian/pages/friends/index_bar.dart';

// page
class FriendsPage extends StatefulWidget {
  FriendsPage({super.key});

  @override
  State<FriendsPage> createState() => _FriendsPageState();
}

class _FriendsPageState extends State<FriendsPage> with AutomaticKeepAliveClientMixin<FriendsPage> {
  final List<Friends> _headerData = [
    Friends(
      assetUrl: "images/xdpy.png",
      name: "新的朋友",
    ),
    Friends(
      assetUrl: "images/ql.png",
      name: "群聊",
    ),
    Friends(
      assetUrl: "images/biaoqian.png",
      name: "标签",
    ),
    Friends(
      assetUrl: "images/gzh.png",
      name: "公众号",
    ),
  ];
  final List<Friends> _listDatas = [];
  // 滚动控制器
  final ScrollController _scrollController = ScrollController();
  // 获取滚动位置
  final Map _groupOffsetMap = {
    INDEX_LETTER[0]: 0.0,
    INDEX_LETTER[1]: 0.0,
  };
  final double _cellHeight = 54.5;
  final double _grounpHeight = 30;

  @override
  void initState() {
    super.initState();
    _listDatas
      ..addAll(datas)
      ..addAll(datas);
    _listDatas.sort((Friends a, Friends b) {
      return a.indexLetter!.compareTo(b.indexLetter!);
    });
    
    var _grounpOffset = _cellHeight * _headerData.length; // 4个header

    for (int i = 0; i < _listDatas.length; i++) {
      if (i < 1) {
        _groupOffsetMap[_listDatas[i].indexLetter!] = _grounpOffset;
        _grounpOffset += _grounpHeight + _cellHeight;
      } else {
        if (_listDatas[i].indexLetter != _listDatas[i - 1].indexLetter) {
          _groupOffsetMap[_listDatas[i].indexLetter!] = _grounpOffset;
          _grounpOffset += _grounpHeight + _cellHeight;
        } else {
          _grounpOffset += _cellHeight;
        }
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('通讯录'),
        backgroundColor: primaryColor,
        centerTitle: true,
        actions: [
          IconButton(
            icon: const Icon(Icons.add),
            onPressed: () {
              // 跳转页面
              Navigator.of(context).push(
                MaterialPageRoute(
                  builder: (BuildContext context) {
                    return DiscoverChildPage(
                      title: '添加朋友',
                    );
                  },
                ),
              );
            },
          ),
        ],
      ),
      body: Stack(
        children: [
          // 主体列表
          Container(
            color: primaryColor,
            child: ListView.builder(
              controller: _scrollController,
              itemCount: _headerData.length + _listDatas.length,
              itemBuilder: (context, index) {
                // 是否显示分组indexLetter
                bool show = index - 4 > 0 &&
                    _listDatas[index - 4].indexLetter ==
                        _listDatas[index - 5].indexLetter;

                return index < _headerData.length
                    ? _FriendCell(
                        assetUrl: _headerData[index].assetUrl,
                        name: _headerData[index].name,
                      )
                    : _FriendCell(
                        imageUrl: _listDatas[index - 4].imageUrl,
                        name: _listDatas[index - 4].name,
                        groupTItle:
                            show ? null : _listDatas[index - 4].indexLetter,
                      );
              },
            ),
          ),
          // 右侧索引栏
          IndexBar(
            indexBarCallBack: (String letter) {
              setState(() {
                _scrollController.animateTo(_groupOffsetMap[letter]!,
                    duration: Duration(microseconds: 100),
                    curve: Curves.easeIn);
              });
            },
          ),
        ],
      ),
    );
  }
  
  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}

// 自定义cell
class _FriendCell extends StatelessWidget {
  String? imageUrl;
  String name;
  String? assetUrl;
  Bool? show;
  String? groupTItle;

  _FriendCell({
    super.key,
    this.assetUrl,
    this.imageUrl,
    this.groupTItle,
    required this.name,
  });

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Container(
          padding: const EdgeInsets.fromLTRB(10, 0, 0, 0),
          height: groupTItle != null ? 30 : 0,
          alignment: Alignment.centerLeft,
          child: Text(groupTItle ?? ""),
        ),
        Container(
          color: Colors.white,
          child: Row(
            children: [
              Container(
                margin: const EdgeInsets.all(10),
                child: assetUrl != null
                    ? Image.asset(
                        assetUrl!,
                        width: 34,
                        height: 34,
                      )
                    : Image.network(
                        imageUrl!,
                        width: 34,
                        height: 34,
                      ),
              ),
              Expanded(
                flex: 1,
                child: Column(
                  children: [
                    Container(
                      alignment: Alignment.centerLeft,
                      height: 54,
                      child: Text(name),
                    ),
                    Container(
                      height: 0.5,
                      color: primaryColor,
                    )
                  ],
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }
}
